package org.wingstudio.controller.admin;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.wingstudio.entity.FileType;
import org.wingstudio.entity.PageBean;
import org.wingstudio.lucene.FileIndex;
import org.wingstudio.service.FileService;
import org.wingstudio.service.FileTypeService;
import org.wingstudio.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件管理模块
 * Created by liao on 16-11-11.
 */

@Controller
@RequestMapping("/user/admin")
public class FileController {

    @Resource
    private FileService fileService;
    @Resource
    private FileTypeService fileTypeService;


    private FileIndex fileIndex=new FileIndex();

    @RequestMapping("/addFile")
    public ModelAndView addFile()throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        List<FileType> fileTypes=fileTypeService.countList();
        modelAndView.addObject("fileTypes",fileTypes);
        modelAndView.setViewName("user/admin/build/file");
        return modelAndView;
    }


    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request,
                         HttpServletResponse response,
                         @RequestParam("file") MultipartFile file, ModelMap model,
                         org.wingstudio.entity.File file2) throws Exception{

        String path = request.getSession().getServletContext().getRealPath("/static/files");
        String pathFilePDF = request.getSession().getServletContext().getRealPath("/static/filesPDF");
        String path2 = request.getSession().getServletContext().getRealPath("/static");
        String testFileName = file.getOriginalFilename();
        String prefix=testFileName.substring(testFileName.lastIndexOf(".")+1);
        String name=String.valueOf(Calendar.getInstance().getTimeInMillis());
        String fileName=name+"."+prefix;
        String fileNamePDF=name+".pdf";
        file2.setFileName(fileNamePDF);
        long fileSize2=file.getSize();
        if((fileSize2/1024)<1000){
            String fileSize3=String.valueOf(fileSize2/1024)+"KB";
            file2.setFileSize(fileSize3);
        }else{
            String fileSize3=String.valueOf(fileSize2/1048576)+"M";
            file2.setFileSize(fileSize3);
        }

        if (prefix.equals("pdf")){
            File targetFile1 = new File(pathFilePDF, fileNamePDF);
            // 保存原文件
            try {
                file.transferTo(targetFile1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            File targetFile2 = new File(path, fileName);
            // 保存原文件
            try {
                file.transferTo(targetFile2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        fileService.add(file2);
        org.wingstudio.entity.File testFile=fileService.getLast();
        System.out.println("test file id:"+testFile.getId()+"test fileTile:"+testFile.getTitle());
        fileIndex.addIndex(testFile);

        if(prefix.equals("doc")||prefix.equals("docx")||prefix.equals("txt")
                ||prefix.equals("excel")){
            try{
                AsposeUtil.docToPdf(path+"/"+fileName,
                        pathFilePDF+"/"+name+".pdf");
            }catch (Exception e){
                System.out.println(e);
            }
        }

        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/policy")
    public ModelAndView listPolicys(@RequestParam(value="page",required=false)String page,
                                  HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("fileTypeId",1);
        List<org.wingstudio.entity.File> policyList=fileService.listFile(map);
        Long sum=fileService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/policy",
                fileService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("policyList",policyList);
        modelAndView.setViewName("user/admin/file/policyManage");
        return modelAndView;
    }

    @RequestMapping("/manage")
    public ModelAndView listManages(@RequestParam(value="page",required=false)String page,
                                  HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("fileTypeId",2);
        List<org.wingstudio.entity.File> manageList=fileService.listFile(map);

        Long sum=fileService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/manage",
                fileService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("manageList",manageList);
        modelAndView.setViewName("user/admin/file/schoolManage");
        return modelAndView;
    }

    @RequestMapping("/house")
    public ModelAndView listHouses(@RequestParam(value="page",required=false)String page,
                                    HttpServletRequest request)
            throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("fileTypeId",3);
        List<org.wingstudio.entity.File> houseList=fileService.listFile(map);

        Long sum=fileService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/house",
                fileService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("houseList",houseList);
        modelAndView.setViewName("user/admin/file/houseManage");
        return modelAndView;
    }

    @RequestMapping("/deleteFile")
    public String deleteFile(@RequestParam(value="id")String id,HttpServletResponse response)
            throws Exception{
        System.out.println("test file id:"+id);
        fileService.delete(Integer.parseInt(id));
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    /**
     * 通过id查找实体
     * @param id
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/findFileById")
    public String findFileById(@RequestParam(value="id")String id,HttpServletResponse response)
            throws Exception{
        org.wingstudio.entity.File file=fileService.findFileById(Integer.parseInt(id));
        JSONObject jsonObject=JSONObject.fromObject(file);
        ResponseUtil.write(response, jsonObject);
        return null;
    }

    @RequestMapping("/updateFile/{id}")
    public ModelAndView get(@PathVariable("id") Integer id)throws Exception{
        ModelAndView modelAndView=new ModelAndView();

        org.wingstudio.entity.File file=fileService.findFileById(id);
        List<FileType> fileTypes=fileTypeService.countList();
        modelAndView.addObject("fileTypes",fileTypes);
        modelAndView.addObject("file",file);
        modelAndView.setViewName("user/admin/update/file");
        return modelAndView;
    }

    @RequestMapping(value = "/updateFile", method = RequestMethod.POST)
    public String updateFile(HttpServletRequest request,
                         @RequestParam("file") MultipartFile file, ModelMap model,
                         org.wingstudio.entity.File file2,
                             HttpServletResponse response) throws Exception{

        if (file.isEmpty()) {
            fileService.update(file2);
            JSONObject result = new JSONObject();
            result.put("success", true);
            ResponseUtil.write(response, result);
            return null;
        } else {

            String path = request.getSession().getServletContext().getRealPath("/static/files");
            String pathFilePDF = request.getSession().getServletContext().getRealPath("/static/filesPDF");
            String path2 = request.getSession().getServletContext().getRealPath("/static");
            String testFileName = file.getOriginalFilename();
            String prefix = testFileName.substring(testFileName.lastIndexOf(".") + 1);
            String name = String.valueOf(Calendar.getInstance().getTimeInMillis());
            String fileName = name + "." + prefix;
            String fileNamePDF = name + ".pdf";
            file2.setFileName(fileNamePDF);
            long fileSize2 = file.getSize();
            if ((fileSize2 / 1024) < 1000) {
                String fileSize3 = String.valueOf(fileSize2 / 1024) + "KB";
                file2.setFileSize(fileSize3);
            } else {
                String fileSize3 = String.valueOf(fileSize2 / 1048576) + "M";
                file2.setFileSize(fileSize3);
            }

            if (prefix.equals("pdf")) {
                File targetFile1 = new File(pathFilePDF, fileNamePDF);
                // 保存原文件
                try {
                    file.transferTo(targetFile1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                File targetFile2 = new File(path, fileName);
                // 保存原文件
                try {
                    file.transferTo(targetFile2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            fileService.add(file2);
            org.wingstudio.entity.File testFile = fileService.getLast();
            System.out.println("test file id:" + testFile.getId() + "test fileTile:" + testFile.getTitle());
            fileIndex.addIndex(testFile);

            if (prefix.equals("doc") || prefix.equals("docx") || prefix.equals("txt")
                    || prefix.equals("excel")) {
                try {
                    AsposeUtil.docToPdf(path + "/" + fileName,
                            pathFilePDF + "/" + name + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            JSONObject result = new JSONObject();
            result.put("success", true);
            ResponseUtil.write(response, result);
            return null;
        }
    }

    @RequestMapping("/searchFile")
    public ModelAndView search(HttpServletRequest request)throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        String content=request.getParameter("content");
        System.out.println("测试传入的值："+content);
        List<org.wingstudio.entity.File> fileList=fileIndex.searchFile(content);
        System.out.println("test newSize:"+fileList.size());

        modelAndView.addObject("fileList",fileList);
        modelAndView.setViewName("user/admin/file/searchResult");
        return modelAndView;
    }
}